package cn.tedu.mall.order.consumer;

import cn.tedu.mall.order.mapper.OrderItemMapper;
import cn.tedu.mall.order.mapper.OrderMapper;
import cn.tedu.mall.order.service.impl.CartServiceImpl;
import cn.tedu.mall.pojo.order.model.OmsOrder;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 1.Component SPRING bean对象
 * 2.接口实现
 * 3.注解,提供属性监听主题,配置分组
 */
@Component
@Slf4j
@RocketMQMessageListener(
        topic = "csmall-tx-cart-delete-topic",
        consumerGroup = "cart-delete-group",
        selectorExpression = "localAdd")
public class CartDeleteConsumer implements RocketMQListener<String> {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void onMessage(String message) {
        //使用sn查询order对象
        OmsOrder order = orderMapper.selectOrderBySn(message);
        //获取userId
        Long userId = order.getUserId();
        //查询到orderId
        Long id = order.getId();
        //使用orderId查询订单商品
        //select oms_order_item.sku_id from oms_order_item where
        //order_id=#{orderId}
        List<String> skuIds = orderItemMapper.selectSkuIdsByOrderId(id);
        //通过redis 操作hash数据中的field删除
        HashOperations<String, Object, Object> hashOperations =
                stringRedisTemplate.opsForHash();
        //userId skuId1 skuId2 skuId3...skuIdN
        String cartKey = CartServiceImpl.ORDER_CART_PREFIX + userId;
        hashOperations.delete(cartKey, skuIds.toArray());
    }
}
